﻿using SCM.Common;
using SCM.Common.Extensions;
using SCM.Model;
using SCM.Model.DBEntity;
using SCM.Servie.IBusiness;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;

namespace SCM.Servie.Business 
{
    /// <summary>
    /// 规则服务
    /// </summary>
    public class RuleService : IRuleService
    {
        private readonly DbContext dal = new DbContext();

        public string Add(T_Rule model)
        {
            return dal.Insertable(model).ExecuteReturnEntity().ID;
        }

        public bool Delete(List<string> ids)
        {
            return dal.Updateable<T_Rule>(new
            {
                DataStatus = DataStatusEnum.Deleted,
                ModifyTime = DateTime.Now,
            }).Where(p => ids.Contains(p.ID)).ExecuteCommand() > 0;
        }

        public T_Rule GetById(string id)
        {
            return dal.Get<T_Rule>(id);
        }

        public List<T_Rule> GetList(string ruleName)
        {
            Expression<Func<T_Rule, bool>> whereExp = (a) => a.DataStatus == DataStatusEnum.Valid;
            if (!string.IsNullOrWhiteSpace(ruleName))
            {
                whereExp = whereExp.Compose((a) => a.RuleName.StartsWith(ruleName), Expression.AndAlso);
            }
            return dal.Queryable<T_Rule>().Where(whereExp).ToList();
        }

        public PageData<T_Rule> Query(string ruleName, PageInfo page)
        {
            int count = 0;
            Expression<Func<T_Rule, bool>> whereExp = (a) => a.DataStatus == DataStatusEnum.Valid;
            if (!string.IsNullOrWhiteSpace(ruleName))
            {
                whereExp = whereExp.Compose((a) => a.RuleName.StartsWith(ruleName), Expression.AndAlso);
            }
            List<T_Rule> list = dal.Queryable<T_Rule>().Where(whereExp).OrderBy(a => a.CreateTime, SqlSugar.OrderByType.Desc).ToPageList(page.PageIndex, page.PageSize, ref count);
            page.DataCount = count;
            return new PageData<T_Rule> { Data = list, Page = page };
        }

        public bool Update(T_Rule model)
        {
            return dal.Modify(model);
        }
    }
}
